package com.company;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @date : 2024-01-09 下午4:08
 */

public class P068_CountFileRows {

    public static void main(String[] args) {
        String filename = "file/countFileRows.txt";
        new Thread(() -> {
            while (true) {
                createFile(filename);
            }
        }).start();

        while (true) {
            int count = countRows(filename);
            if (count == 0) {
                System.out.println(0);
            } else if (count == 1) {
                System.out.println(1);
            } else if (count == 2) {
                System.out.println(2);
            } else if (count == 3) {
                System.out.println(3);
            } else {
                System.out.println(count);
                break;
            }
        }
    }


    private static void createFile(String filename) {
        try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(Paths.get(filename))))) {
            bw.write("123");
            bw.flush();
            bw.newLine();
            bw.write("456");
            bw.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static int countRows(String filename) {
        int ans = 0;
        try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
            while (br.readLine() != null) {
                ans++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ans;
    }
}
